﻿<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>首字母变为大写</title>
    <script type="text/javascript" language="JavaScript">
        function changeCase(frmObj){
            var index;
            var tmpStr;
            var tmpChar;
            var preString;
            var postString;
            var strlen;
            tmpStr = frmObj.value.toLocaleString(); // 转换为全部小写
            strlen = tmpStr.length;     // 字符的长度
            if(strlen > 0){
                for(index = 0;index < strlen;index++){
                    if(index === 0){
                        // 将第一位字符转换为大写
                        tmpChar = tmpStr.substring(0,1).toUpperCase();
                        postString = tmpStr.substring(1,strlen);
                        tmpStr = tmpChar + postString;
                    }else{
                        tmpChar = tmpStr.substring(index, index+1);
                        //如果是第二个单词（通过空格判断）
                        if(tmpChar === " " && index < (strlen -1)){
                            tmpChar = tmpStr.substring(index+1, index+2).toUpperCase();
                            preString = tmpStr.substring(0, index+1);
                            postString = tmpStr.substring(index+2,strLen);
                            tmpStr = preString + tmpChar + postString;
                        }
                    }
                }
            }
            frmObj.value = tmpStr;  //显示转换后的文本
        }
        
    </script>
</head>
<body>

<input type=text name="txt1" value="this is test!">
<input type=button value="转换文本" onClick="javascript:changeCase(txt1)">

</body>
</html>